using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SelfAnim2 : MonoBehaviour
{
    public enum Anim_Dir
    {
        Right,
        Left,
        Up,
        Down
    }

    public float AnimSpeed;
    public Sprite[] spriteArr;

    private SpriteRenderer spriteRender;
    private int currFrame = 0;
    private Coroutine animCoroutine;
    private Anim_Dir currentDirection = Anim_Dir.Right; 

    private int framesPerDir = 2; 

    void Start()
    {
        if (spriteArr.Length < framesPerDir * 4)  
        {
            Debug.LogError("Not enough sprites in spriteArr for all directions!");
            return;
        }

        spriteRender = GetComponent<SpriteRenderer>();
        animCoroutine = StartCoroutine(PlayAnim());
    }

    IEnumerator PlayAnim()
    {
        while (true)
        {
            yield return new WaitForSeconds(AnimSpeed);
            currFrame = (currFrame + 1) % framesPerDir;
            int index = (int)currentDirection * framesPerDir + currFrame;
            spriteRender.sprite = spriteArr[index];
        }
    }

     
    public void ChangeDir(Anim_Dir newDir)
    {
        currentDirection = newDir;
        currFrame = 0; 
    }

    

    void OnDestroy()
    {
        if (animCoroutine != null)
        {
            StopCoroutine(animCoroutine);
        }
    }
}